package com.service.impl;

import com.dto.UserDTO;
import com.mapper.NotificationsMapper;
import com.mapper.UsersMapper;
import com.pojo.Notifications;
import com.pojo.Result;
import com.pojo.Users;
import com.service.NotificationsService;
import com.vo.NotificationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class NotificationsServiceImpl implements NotificationsService {

    @Autowired
    private NotificationsMapper notificationsMapper;

    @Autowired
    private UsersMapper usersMapper; // 用于查询用户信息

    @Override
    public Result<Void> createNotification(Notifications notification) {
        try {
            notification.setCreatedAt(LocalDateTime.now());
            if (notification.getRead() == null) {
                notification.setRead(false);
            }
            int result = notificationsMapper.insert(notification);
            return result > 0 ? Result.success() : Result.error("创建通知失败");
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<Void> updateNotification(Notifications notification) {
        try {
            int result = notificationsMapper.update(notification);
            return result > 0 ? Result.success() : Result.error("更新通知失败，可能ID不存在");
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<Void> deleteNotification(Integer id) {
        try {
            int result = notificationsMapper.delete(id);
            return result > 0 ? Result.success() : Result.error("删除通知失败，可能ID不存在");
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<Notifications> getNotificationById(Integer id) {
        try {
            Notifications notification = notificationsMapper.selectById(id);
            return notification != null ? Result.success(notification) : Result.error("通知不存在");
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<List<Notifications>> getNotificationsByUserId(Integer userId) {
        try {
            List<Notifications> notifications = notificationsMapper.selectByUserId(userId);
            return Result.success(notifications);
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<List<Notifications>> getUnreadNotifications(Integer userId) {
        try {
            List<Notifications> notifications = notificationsMapper.selectByUserIdAndReadStatus(userId, false);
            return Result.success(notifications);
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<Void> markNotificationAsRead(Integer id) {
        try {
            int result = notificationsMapper.markAsRead(id);
            return result > 0 ? Result.success() : Result.error("标记为已读失败，可能ID不存在");
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<Void> markAllNotificationsAsRead(Integer userId) {
        try {
            int result = notificationsMapper.markAllAsRead(userId);
            return result > 0 ? Result.success() : Result.error("标记所有通知为已读失败，可能用户没有通知");
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    /**
     * 新增：把 Notifications 实体转换成 VO（用于 WebSocket 实时推送）
     */
    @Override
    public Result<NotificationVO> getNotificationVO(Notifications notification) {
        try {
            NotificationVO vo = new NotificationVO();
            vo.setId(notification.getId());
            vo.setType(notification.getType());
            vo.setSourceId(notification.getSourceId());
            vo.setTargetId(notification.getTargetId());
            vo.setIsRead(notification.getRead());
            vo.setCreatedAt(notification.getCreatedAt());

            // 查询操作发起者的用户信息
            Users relatedUser = usersMapper.selectUserById(Long.valueOf(notification.getSourceId()));
            if (relatedUser != null) {
                UserDTO userDTO = new UserDTO();
                userDTO.setId(relatedUser.getId());
                userDTO.setNickname(relatedUser.getNickname());
                userDTO.setAvatarUrl(relatedUser.getAvatarUrl());
                vo.setRelatedUser(userDTO);
            }

            // 根据类型生成提示文案
            switch (notification.getType()) {
                case "LIKE":
                    vo.setContent(vo.getRelatedUser().getNickname() + " 点赞了你的笔记");
                    break;
                case "FOLLOW":
                    vo.setContent(vo.getRelatedUser().getNickname() + " 关注了你");
                    break;
                case "COMMENT":
                    vo.setContent(vo.getRelatedUser().getNickname() + " 评论了你的笔记");
                    break;
                case "REPLY":
                    vo.setContent(vo.getRelatedUser().getNickname() + " 回复了你的评论");
                    break;
                default:
                    vo.setContent("你收到一条新通知");
            }

            return Result.success(vo);
        } catch (Exception e) {
            return Result.error(500, "获取通知VO失败: " + e.getMessage());
        }
    }
}